#!/bin/bash
# /**
# * Copyright (c) 2018, yzfcer@163.com
# * All rights reserved.
# * @file    find.sh
# * @brief   查看符合规则的文件
# * @author  Jason Zhou,yzfcer@163.com
# * @version 1.0
# * @date    2021-09-15
# */


# 全局变量：存储过滤条件
declare -A filters
declare dir  # 查找根目录

# 1. 显示帮助信息（英文）
show_help() {
    cat << EOF
Usage: $0 <dir> [options]

Options:
  <dir>             Required. Specify the root directory for searching
  -t <filetype>     Filter by file type (suffix), e.g., txt, sh
  -s <str>          Filter files containing the specified string (literal match)
  -w <word>         Filter files containing the specified whole word (word boundary)
  --prefix <prefix> Filter files whose names start with the specified prefix
  --suffix <suffix> Filter files whose names end with the specified suffix
  -h, --help        Show this help message

Examples:
  $0 /home -t sh -s "function"        # Search /home for .sh files containing "function"
  $0 . --prefix "log_" --suffix ".txt" # Search current dir for files starting with "log_" and ending with ".txt"
EOF
}

# 2. 解析命令行参数
parse_args() {
    if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" ]]; then
        show_help
        exit 0
    fi

    # 提取根目录
    dir="$1"
    shift

    # 解析选项
    while [[ $# -gt 0 ]]; do
        case "$1" in
            -t)
                filters[filetype]="$2"
                shift 2
                ;;
            -s)
                filters[str]="$2"
                shift 2
                ;;
            -w)
                filters[word]="$2"
                shift 2
                ;;
            --prefix)
                filters[prefix]="$2"
                shift 2
                ;;
            --suffix)
                filters[suffix]="$2"
                shift 2
                ;;
            *)
                echo "Error: Unknown option '$1'" >&2
                show_help
                exit 1
                ;;
        esac
    done
}

# 3. 验证目录合法性
validate_dir() {
    if [[ ! -d "$dir" ]]; then
        echo "Error: Directory '$dir' does not exist or is not a directory" >&2
        exit 1
    fi
}

# 4. 构建文件名过滤的find命令
build_filename_filter() {
    local find_cmd="find '$dir' -type f"  # Only search for regular files

    # Filter by file type (suffix)
    if [[ -n "${filters[filetype]}" ]]; then
        find_cmd+=" -name '*.'${filters[filetype]}"
    fi

    # Filter by prefix
    if [[ -n "${filters[prefix]}" ]]; then
        find_cmd+=" -name '${filters[prefix]}*'"
    fi

    # Filter by suffix (higher priority than file type)
    if [[ -n "${filters[suffix]}" ]]; then
        find_cmd+=" -name '*${filters[suffix]}'"
    fi

    echo "$find_cmd"
}

# 5. 按内容过滤文件
filter_by_content() {
    local files="$1"

    # Filter by string content
    if [[ -n "${filters[str]}" ]]; then
        files=$(echo "$files" | xargs grep -lF "${filters[str]}" 2>/dev/null)
    fi

    # Filter by whole word
    if [[ -n "${filters[word]}" ]]; then
        # Escape special characters to avoid grep regex errors
        local safe_word=$(printf "%q" "${filters[word]}")
        files=$(echo "$files" | xargs grep -lE "\b${safe_word}\b" 2>/dev/null)
    fi

    echo "$files"
}

# 6. 主函数：串联所有流程
main() {
    parse_args "$@"
    validate_dir

    # Step 1: Filter by filename/type
    local find_cmd=$(build_filename_filter)
    local candidate_files=$(eval "$find_cmd" 2>/dev/null)  # Ignore permission errors

    # Step 2: Filter by content
    local result_files=$(filter_by_content "$candidate_files")

    # Output results
    echo "$result_files"
}

# 启动主流程
main "$@"
